/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.model;

import java.io.File;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.emory.mathcs.backport.java.util.Collections;

public class BlastdbProgramModifier implements ProgramModifier
{
	public static String BLASTDB;
	public static Pattern pat = Pattern.compile("^(.+?)(\\.\\d\\d)?\\.(p|n)\\w\\w$");

	public void modifyProgram(Program program)
	{
		Set<String> proteins = new HashSet<String>();
		Set<String> nucleotide = new HashSet<String>();
		File dbdir = new File(BLASTDB);
		List<String> p = new LinkedList<String>();
		List<String> n = new LinkedList<String>();
		if (dbdir.exists() && dbdir.isDirectory())
		{
			for (File file : dbdir.listFiles())
			{
				if (file.isDirectory())
				{
					continue;
				}
				String name = file.getName();
				Matcher m = pat.matcher(name);
				if (m.matches())
				{
					String dbname = m.group(1);
					String nOrP = m.group(3);
					if (nOrP.equals("p"))
						proteins.add(dbname);
					else
						nucleotide.add(dbname);
				}
			}
			
			p.addAll(proteins);
			Collections.sort(p);
			n.addAll(nucleotide);
			Collections.sort(n);
		}
		Parameter parameter1 = program.getParameter("protein_db");
		if (parameter1 != null)
		{
			Vlist vlist = new Vlist();
			for (String db : p)
			{
				vlist.getLabel().add(db);
				vlist.getValue().add(db);
			}
			parameter1.setVlist(vlist);
		}
		Parameter parameter2 = program.getParameter("nucleotid_db");
		if (parameter2 != null)
		{
			Vlist vlist = new Vlist();
			for (String db : n)
			{
				vlist.getLabel().add(db);
				vlist.getValue().add(db);
			}
			parameter2.setVlist(vlist);
		}

	}

}
